var config = {

    logoMargin: 10,
    logoBorderWidth: 3,
    logoBorderRadius: 10,
    logoVerticalOffset: 50,
    fontSize: '20px',
    indent: '50px',
    pixelsBetweenItems: '50px',
    earthColor: '#855723',
    greenColor: '#74C365',
    blueColor: '#87CEEB'
}

var info = {

}

function onResize(){

    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();
}

function onPageLoad() {
    
    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();

    initializeModalBox();

    makeLogoPretty();
    
    makeIntroTextPretty();

    makeAttendanceSheetElements();

    makeEmailReminderListElements();

    makeWeeklySummaryElements();

    makeDeadbeatElements();

    getLocations();

    $('.divider').height( 50 );

}

function makeDeadbeatElements() {

    $('#deadbeatContainer').append(
        makeEl('div').attr( { 'class': 'getDataButton' } )
                     .text('Get emails of they who have not paid.')
                     .bind( 'click', { }, getDeadbeats ),
        getClearDiv() );
}

function getDeadbeats() {

    showModalWait();

    $.ajax( { url: 'http://patchworkgardens.net/cgi-bin/getDeadbeats.py',
              type: 'GET',
              error: handleAjaxError,
              success: handleCopyPastaResponse } );
}

function makeWeeklySummaryElements() {

    $('#weeklySummaryContainer').append(
        getWeekDropDown( 'weeklySummaryDropDown' ),
        makeEl('div').attr( { 'class': 'getDataButton' } )
                     .text('Get weekly summary copy/pasta.')
                     .bind( 'click', { }, getWeeklySummary ),
        getClearDiv()
    );
}

function getWeeklySummary() {

    showModalWait();

    var url = [ 'http://patchworkgardens.net/cgi-bin/getWeeklySummary.py?week=',
                        encodeURIComponent( $('#weeklySummaryDropDown').val() ),
                        '&date=',
                        encodeURIComponent( $('#weeklySummaryDropDown option:selected').text() ) 
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleAjaxError,
              success: handleCopyPastaResponse } );
}

function makeEmailReminderListElements() {

    $('#emailReminderContainer').append(
        getWeekDropDown( 'emailReminderDropDown' ),
        makeEl('div').css( { 'float': 'left', 'line-height': '40px', 'padding': '5px' } ).append(
            makeEl('select').attr( { 'id': 'emailReminderDayDropDown' } ).append(
                makeEl('option').attr( { 'value': 'wednesday' } ).text( 'Wednesday' ),
                makeEl('option').attr( { 'value': 'thursday' } ).text( 'Thursday' ),
                makeEl('option').attr( { 'value': 'friday' } ).text( 'Friday' )
            )
        ),
        makeEl('div').attr( { 'class': 'getDataButton' } )
                     .text('Get pickup / absentee email lists.')
                     .bind( 'click', { }, getPickupAndAbsenteeLists ),
        getClearDiv() );
        
}

function getPickupAndAbsenteeLists() {

    showModalWait();

    var url = [ 'http://patchworkgardens.net/cgi-bin/getPickupAndAbsenteeLists.py?week=',
                        encodeURIComponent( $('#emailReminderDropDown').val() ),
                        '&dayOfWeek=',
                        encodeURIComponent( $('#emailReminderDayDropDown').val() ),
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleAjaxError,
              success: handleCopyPastaResponse } );


}

function getAttendanceSheet() {

    showModalWait();

    var url = [ 'http://patchworkgardens.net/cgi-bin/getAttendanceSheet.py?week=',
                        encodeURIComponent( $('#attendanceSheetWeekDropDown').val() ),
                        '&location=',
                        encodeURIComponent( $('#attendanceSheetLocationDropDown').val() ),
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleAjaxError,
              success: handleCopyPastaResponse } );
}

function showModalWait() {

    info.modalText = makeEl('div').attr( { 'class': 'modalText' } ).text( 'Please Wait.' );
    
    $('#modalBoxTitle').text( '' );
    $('#modalBoxForm').append( info.modalText );
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleCopyPastaResponse( response ) {

    $('#modalBoxTitle').text( 'This is your copy/pasta' );
   
    info.modalText.remove();

    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).html( response ) );

    alignModalBox();

    $( document ).bind( 'keydown', handleModalKeyPress );
    $( document ).bind( 'click', handleModalMouseClick );
}

function handleAjaxError() {

    $('#modalBoxTitle').text( 'Ehhhh' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( 'There was an error retrieving the copy/pasta.  It is a bug ( ~_~ ) if it happens everytime, it is the fault of iPage if it happens intermittently.' ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function makeAttendanceSheetElements() {

    $('#attendanceContainer').append(
        makeEl('div').css( { 'float': 'left', 'line-height': '40px', padding: '5px' } ).append(
            makeEl('select').attr( { 'id': 'attendanceSheetLocationDropDown' } )
        ),
        getWeekDropDown( 'attendanceSheetWeekDropDown' ),
        makeEl('div').attr( { 'class': 'getDataButton' } )
                     .text('Get Attendance Copy/Pasta')
                     .bind( 'click', { }, getAttendanceSheet ),
        getClearDiv() );

}

function getClearDiv() {

    return makeEl('div').css( { 'clear': 'both' } );
}

function getWeekDropDown( id ) {
        
        return makeEl('div').css( { 'float': 'left', 'line-height': '40px', padding: '5px' } ).append(
            makeEl('select').attr( { 'id': id } ).append(
                makeEl('option').attr( { 'value': 'week1' } ).text( 'May 15/16' ),
                makeEl('option').attr( { 'value': 'week2' } ).text( 'May 22/23' ),
                makeEl('option').attr( { 'value': 'week3' } ).text( 'May 29/30' ),
                makeEl('option').attr( { 'value': 'week4' } ).text( 'June 5/6' ),
                makeEl('option').attr( { 'value': 'week5' } ).text( 'June 12/13' ),
                makeEl('option').attr( { 'value': 'week6' } ).text( 'June 19/20' ),
                makeEl('option').attr( { 'value': 'week7' } ).text( 'June 26/27' ),
                makeEl('option').attr( { 'value': 'week8' } ).text( 'July 3/4' ),
                makeEl('option').attr( { 'value': 'week9' } ).text( 'July 10/11' ),
                makeEl('option').attr( { 'value': 'week10' } ).text( 'July 17/18' ),
                makeEl('option').attr( { 'value': 'week11' } ).text( 'July 24/25' ),
                makeEl('option').attr( { 'value': 'week12' } ).text( 'July/Aug 31/1' ),
                makeEl('option').attr( { 'value': 'week13' } ).text( 'Aug 7/8' ),
                makeEl('option').attr( { 'value': 'week14' } ).text( 'Aug 14/15' ),
                makeEl('option').attr( { 'value': 'week15' } ).text( 'Aug 21/22' ),
                makeEl('option').attr( { 'value': 'week16' } ).text( 'Aug 28/29' ),
                makeEl('option').attr( { 'value': 'week17' } ).text( 'Sept 4/5' ),
                makeEl('option').attr( { 'value': 'week18' } ).text( 'Sept 11/12' ),
                makeEl('option').attr( { 'value': 'week19' } ).text( 'Sept 18/19' ),
                makeEl('option').attr( { 'value': 'week20' } ).text( 'Sept 25/26' )
            )
        )
}

function getLocations() {

    $.ajax( { url: 'http://patchworkgardens.net/cgi-bin/getLocations.py',
              type: 'GET',
              error: handleGetLocationsError,
              success: handleGetLocationsResponse } );

    $('#modalBoxTitle').text( '' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( 'Getting Location data...' ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleGetLocationsError() {

    $('#modalBoxTitle').text( 'Ehhhh' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( 'There was an error retrieving the location data.  My son, refresh the page.' ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleGetLocationsResponse( response ) {

    var locationData = eval( '(' + response + ')' );

    for( var i = 0, ii = locationData.length; i < ii; i++ ) {
        
        $('#attendanceSheetLocationDropDown').append(
            makeEl('option').attr( { 'value': locationData[i].id } ).text( locationData[i].name ) );
    }

    closeModalBox();
}


function showModalText( text ) {
 
    $('#modalBoxTitle').text( 'Not so fast' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( text ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleSubmitClick() {

    $('.submitButton').unbind('click');
    
    if( ! info.currentCustomerId ) { showModalText( 'Unable to find a customerId - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#amountPaid').text() ) { showModalText( 'Unable to find amount paid - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#amountOwed').text() ) { showModalText( 'Unable to find amount owed - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#emailAddress').text() ) { showModalText( 'Unable to find emailAddress - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( parseFloat( $('#newPayment').val() ) == 0 ) { showModalText( 'Received Payment is $0.00.  Try again my son.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }

    var url = [ 'http://patchworkgardens.net/cgi-bin/weGotCash.py?customerId=',
                        encodeURIComponent( info.currentCustomerId ),
                        '&amountPaid=',
                        encodeURIComponent( $('#amountPaid').text() ),
                        '&amountOwed=',
                        encodeURIComponent( $('#amountOwed').text() ),
                        '&emailAddress=',
                        encodeURIComponent( $('#emailAddress').text() ),
                        '&newPayment=',
                        encodeURIComponent( $('#newPayment').val() ) 
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleErrorResponse,
              success: handleSubmitResponse } );

    showModalWait();   
}

function handleErrorResponse() {

    $( $('#modalBoxForm div.modalText')[0] ).text( "There was an error.  Try again.  If it happens three times in a row, its probably a bug." );
    info.modalWait = false;
    alignModalBox();
}

function makeLogoPretty() {

    $('#logoImage')
        .css( { 'float': 'left',
                'background-image': 'url(Images/jsLogo.png)',
                'height': '209px',
                'width': '540px',
                'margin': [ config.logoMargin, 'px' ].join('') } );
    
    $('#logoBorder3').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.earthColor ].join('') } );
    
    $('#logoBorder2').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.greenColor ].join('') } );
    
    $('#logoBorder1').css( { 'float': 'left',
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.blueColor ].join('') } );

    $('#logoContainer')
        .height( $('#logoBorder1').outerHeight( true ) )
        .width( $('#logoBorder1').outerWidth( true ) )
        .css( { 'float': 'left',
                'margin-top': '20px',
                'margin-left': ( ( info.documentWidth - $('#logoBorder1').outerWidth( true ) ) / 2 ) } )
        .after( makeEl('div').css( { 'clear': 'both' } ) );
}

function initializeModalBox() {

    $('body').append(
        makeEl('div').attr( { 'id': 'modalBoxContainer' } ).append(
            makeEl('div').attr( { 'class': 'modalBoxOverlay' } ),
            makeEl('div').attr( { 'id': 'modalBoxContent' } ).css( { 'overflow': 'auto' } ).append(
                makeEl('div').attr( { 'id': 'modalBoxTitle' } ),
                makeEl('div').attr( { 'id': 'modalBoxForm' } ) ) ) );
}

function makeIntroTextPretty() {

    $( '#introductionText' ).css( { 'margin-top': '30px',
                                    'min-width': '1036px',
                                    'overflow': 'hidden' } );
    
    $( '.introductionText' ).css( { 'text-align': 'center', 'font-size': '20px' } );
}
   
function alignModalBox() {

    var content = $('#modalBoxContent');
    var form = $('#modalBoxForm');
    
    if( content.outerHeight( true ) > info.documentHeight ) {

        content.height( info.documentHeight * .75 );
    }
    
    if( content.outerWidth( true ) > info.documentWidth ) {

        content.width( info.documentWidth * .75 );
    }

    content.css( { top: ( ( info.documentHeight - content.outerHeight( true ) ) / 2 ),
                   left: ( ( info.documentWidth - content.outerWidth( true ) ) / 2 ) } );

}

function handleModalKeyPress( e ) { if( e.keyCode == 27 ) { closeModalBox(); } }

function handleModalMouseClick( e ) {

    if( ! ( isMouseOnElement( { x: e.pageX, y: e.pageY, el: $( '#modalBoxContent' ) } ) ) ) { closeModalBox(); }
}

function isMouseOnElement( p ) {

    var elementOffset = p.el.offset();

    if( p.x < elementOffset.left || p.y < elementOffset.top ||
        p.x > ( elementOffset.left + p.el.outerWidth( true ) ) ||
        p.y > ( elementOffset.top + p.el.outerHeight( true ) ) ) {

        return false;

    } else { return true; }
}

function closeModalBox() {

    $('#modalBoxTitle').text('');

    $('#modalBoxForm').empty();

    $('#modalBoxContainer').hide();
    
    $(document).unbind( 'keydown', handleModalKeyPress );
    $(document).unbind( 'click', handleModalMouseClick );
}

function makeEl( elementName ) { return $(document.createElement(elementName)); }
function setMouseToPointer() { document.body.style.cursor = 'pointer'; }
function setMouseToDefault() { document.body.style.cursor = 'default'; }


$( window ).load( onPageLoad );
$( window ).resize( onResize );
